package com.etalk.crm.controller;

import com.etalk.crm.pojo.KnowledgePointClassification;
import com.etalk.crm.pojo.StudentReportCustomizeDetail;
import com.etalk.crm.service.StudentReportCustomizeService;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.*;

/**
 * @author Jordan
 */
@Controller
@RequestMapping("/student/report")
public class StudentReportController {
    private static final Logger logger = LogManager.getLogger(StudentReportController.class);
    @Resource
    private StudentReportCustomizeService studentReportCustomizeService;

    @Value("${web.crm.h5.url}")
    private String h5Url;

    /**
     * 初始化自定义时间段学习报表的页面
     * @param model 页面数据
     * @param personId 学员id
     * @return 页面
     */
    @RequestMapping(value = "/show/{personId}",method = {RequestMethod.GET})
    public String showStudentReportByCustomize(Model model,@PathVariable("personId") int personId,String tokenString){
        model.addAttribute("webUrl",h5Url);
        model.addAttribute("personId",personId);
        model.addAttribute("tokenString",tokenString);
        return "student/student_report_customize";
    }
    /**
     * 生成自定义时间段学习报表
     * @param model 页面数据
     * @param personId 用户id
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @param session 当前会话数据
     * @return 页面
     */
    @RequestMapping(value = "/create",method = {RequestMethod.POST})
    public String createStudentReportByCustomize(Model model, @RequestParam int personId, @RequestParam String startDate, @RequestParam String endDate
            , String tokenString,HttpSession session) throws ParseException {
        model.addAttribute("startDate",startDate);
        model.addAttribute("endDate",endDate);
        try {
            int num=studentReportCustomizeService.createReportByCustomize(personId, DateUtils.parseDate(startDate,"yyyy-MM-dd HH:mm:ss"), DateUtils.parseDate(endDate,"yyyy-MM-dd HH:mm:ss"),session.getAttribute("loginname").toString());
            if (num>0){
                model.addAttribute("status",1);
            }else {
                model.addAttribute("status", 0);
                if (num == -1) {
                    model.addAttribute("errMsg", "选择的时间段学习报表已存在");
                } else {
                    model.addAttribute("errMsg", "创建报表失败，时间段内没有课程数据");
                }
            }
        }catch (DuplicateKeyException e){
            model.addAttribute("status",0);
            model.addAttribute("errMsg","选择的时间段学习报表已存在");
            logger.error(e);
        }

        return this.showStudentReportByCustomize(model,personId,tokenString);
    }

    @GetMapping("/init/check/feedback/{personId}")
    public String initStudentReportByCustomize(Model model, @PathVariable int personId) {

        model.addAttribute("personId",personId);
        model.addAttribute("isClose",false);
        Map<String,Object> map=studentReportCustomizeService.searchMistakeKnowledgeByPersonId(personId);
        model.addAllAttributes(map);
        return "student/student_feedback_create";
    }

    @RequestMapping(value = "/create/feedback",method = {RequestMethod.POST})
    public String createStudentReportByFeedback(Model model, @RequestParam int personId, @RequestParam String startDate, @RequestParam String endDate
            , StudentReportCustomizeDetail record,HttpSession session) throws ParseException {
        Date startTime=DateUtils.parseDate(startDate,"yyyy-MM-dd HH:mm:ss");
        Date endTime=DateUtils.parseDate(endDate,"yyyy-MM-dd HH:mm:ss");
        model.addAttribute("startTime",startTime);
        model.addAttribute("endTime",endTime);
        model.addAttribute("personId",personId);

        try {
            int num=studentReportCustomizeService.createFeedback(personId, startTime, endTime,session.getAttribute("loginname").toString(),record);
            if (num>0){
                model.addAttribute("status",1);
                model.addAttribute("isClose",true);
            }else {
                model.addAttribute("status", 0);
                model.addAttribute("errMsg", "创建阶段检测反馈失败");
            }
        }catch (DuplicateKeyException e){
            model.addAttribute("status",0);
            model.addAttribute("errMsg","本次阶段检测反馈已存在");
            logger.error(e);
        }

        return this.getStudentReportByFeedback(model,record.getId());
    }

    @GetMapping(value = "/feedback/view")
    public String getStudentReportByFeedback(Model model, @RequestParam int feedbackId) {

        StudentReportCustomizeDetail result=studentReportCustomizeService.searchFeedbackInfoById(feedbackId);
        if (result!=null){
            model.addAttribute("feedbackTable",result);
        }else {
            model.addAttribute("status", 0);
            model.addAttribute("errMsg", "获取阶段检测反馈信息失败");
        }

        return "student/student_feedback_view";
    }

    @ResponseBody
    @RequestMapping(value = "/list/classification/{id}",method = {RequestMethod.POST},produces = "application/json;charset=utf-8")
    public Map<String,Object> searchKnowledgePointClassificationListByParentId(@PathVariable("id") Integer id){
        Map<String,Object> resultMap=new HashMap<>(2);
        List<KnowledgePointClassification> list=studentReportCustomizeService.searchKnowledgePointClassificationListByParentId(id);
        resultMap.put("data",list);
        resultMap.put("status",1);
//        logger.info(JSON.toJSONString(list));
        return resultMap;
    }

    @ResponseBody
    @PostMapping(value = "/list/knowledge/{textbookId}",produces = "application/json;charset=utf-8")
    public Map<String,Object> getKnowledgeByTextbook(@PathVariable int textbookId){
        Map<String,Object> resultMap=new HashMap<>(2);
        List<String> list=studentReportCustomizeService.searchKnowledgeListByTextbookId(textbookId);
        resultMap.put("data",list);
        resultMap.put("status",1);
        return resultMap;
    }

    @ResponseBody
    @PostMapping(value = "/study/content/{gradeId}",produces = "application/json;charset=utf-8")
    public Map<String,Object> getStudySuggestions(@PathVariable int gradeId, @RequestParam("knowledgeId") List<Integer> knowledgeId){
        Map<String,Object> resultMap=new HashMap<>(2);
        List<Map<String,Object>> list=studentReportCustomizeService.searchStudySuggestionsKnowledgeByKnowledgeId(gradeId,knowledgeId);
        resultMap.put("data",list);
        resultMap.put("status",1);
        return resultMap;
    }
}
